package me.algo.array;

/**
 * @author guozheng
 * @date 2024/5/7
 */
public class A9 {


    public int findMin(int[] nums) {
        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            int mid = (left + right) >> 1;
            if (nums[mid] < nums[right]) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return nums[left];
    }

    public static void main(String[] args) {
        int[] ints = {5,7,7,8,8,10};
        int[] range = searchRange(ints, 6);
        System.out.println(range);
    }

    public static int[] searchRange(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return new int[]{-1, -1};
        }
        int left = 0;
        int right = nums.length - 1;
        if (target < nums[left] || target > nums[right]) {
            return new int[]{-1, -1};
        }
        if (nums.length == 1) {
            if (nums[0] == target) {
                return new int[]{0, 0};
            }
            return new int[]{-1, -1};
        }
        int md = -1;
        while (left <= right) {
            if (left == right && nums[left] != target) {
                break;
            }
            int mid = (left + right) >> 1;
            if (nums[mid] > target) {
                right = mid;
                continue;
            }
            if (nums[mid] < target) {
                left = mid + 1;
                continue;
            }
            if (nums[mid] == target) {
                md = mid;
                break;
            }

        }
        if (md == -1) {
            return new int[]{-1, -1};
        }
        int l = md, r = md;
        while (l >= 0 || r <= nums.length - 1) {
            if (l > 0 && nums[l - 1] == target) {
                l--;
            }
            if (r < (nums.length - 1) && nums[r + 1] == target) {
                r++;
            }
            if ((l == 0 || nums[l - 1] != target) && (r == (nums.length - 1) || nums[r + 1] != target)) {
                break;
            }
        }
        return new int[]{l, r};
    }

}
